<%--
  Created by IntelliJ IDEA.
  User: David
  Date: 2019/12/16
  Time: 14:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<html>
<head>
    <title>数据表管理</title>
    <script type="text/javascript" src="js/base-loading.js"></script>
    <link rel="stylesheet" type="text/css" href="jquery/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="jquery/themes/icon.css">
    <script type="text/javascript" src="jquery/jquery-3.5.1.min.js"></script>
    <script type="text/javascript" src="jquery/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="jquery/jquery_add_tab.js"></script>
    <script type="text/javascript" src="jquery/locale/easyui-lang-zh_CN.js"></script>
    <style type="text/css">
        .demo-info {
            background: #FFFEE6;
            color: #8F5700;
            padding: 9px;
            margin-bottom: 2px;
            height: 10px;
            font-size: 12px
        }

        .demo-tip {
            width: 16px;
            height: 16px;
            margin-right: 8px;
            float: left;
        }

        .infoTitle {
            color: #3872f6;
            font-size: 15px;
            margin-left: 15px;
        }
    </style>
</head>
<body>
<%--<div class="demo-info">--%>
<%-- <div class="demo-tip icon-tip">&nbsp;</div>--%>
<%--<div>
    此模块为基础信息维护,管理着公共导入功能数据表 &nbsp<font style="font-weight: bold;" color=red>操作请慎重</font>。
</div>--%>
<%--</div>--%>


<div id="uploadWidnow" class="easyui-window" title="数据导入"
     style="width:500px;height:90px;padding: 10px"
     data-options="iconCls:'icon-excel-import',modal:true,collapsible:false,minimizable:false,maximizable:false,closed:true">
    <div id="fileUpLoad">
        <form id="uploadForm" action="${serverUrl}/tableManage/checkFile" method="POST" enctype="multipart/form-data"
              style="display: inline-block;">
            文件导入：<input type="file" id="uploadCheckFile" size="45" name="uploadFile" class="input"
                            onchange="fileSelected()"/>
            <input type="hidden" id="tableCheckId" name="tableId">
            <input type="hidden" id="loginCheckId" name="loginId">
        </form>
        <button id="importId" onclick="$.messager.progress({text:'正在解析中......'}); $('#uploadForm').submit()">导入
        </button>
    </div>
</div>

<div class="easyui-layout" style="width:100%;height:100%;">

    <div data-options="region:'center',title:'数据表一览'" fit=true style="height: 100%;">
        <table id="tableGrid" style="height: 100%;"></table>
        <div id="tableGridToolbar">
            表名:
            <input type="text" style="width:173px;height:21px" id="queryTableEn" name="tableEn">
            表中文名:
            <input type="text" style="width:173px;height:21px" id="queryTableCn" name="tableCn">
            <a class="easyui-linkbutton" iconCls="icon-search" onclick="queryBytableEnAndtableCn()">查询</a>

            <a href="javascript:;" onclick="showColumnDesign()" class="easyui-linkbutton"
               data-options="iconCls:'icon-more',plain:true">查看表结构</a>
            <a href="javascript:;" onclick="addTable()" class="easyui-linkbutton"
               data-options="iconCls:'icon-add',plain:true">新建数据表</a>
            <a href="javascript:;" onclick="resetTable()" class="easyui-linkbutton"
               data-options="iconCls:'icon-edit',plain:true">修改数据表</a>
            <a href="javascript:;" onclick="removeTable()" class="easyui-linkbutton"
               data-options="iconCls:'icon-remove',plain:true">删除数据表</a>
            <%-- <a href="javascript:;" onclick="upLoadeValidate()" class="easyui-linkbutton"
                data-options="iconCls:'icon-application_put',plain:true">上传校验文件</a>--%>
            <a href="javascript:;" onclick="templateMag()" class="easyui-linkbutton"
               data-options="iconCls:'icon-table_gear',plain:true">导入模板管理</a>
            <%--<a href="javascript:;" onclick="addToMenu()" class="easyui-linkbutton"
               data-options="iconCls:'icon-manage',plain:true">添加到菜单</a>--%>
            <%--      <a href="javascript:;" onclick="openPanelDialog()" class="easyui-linkbutton"
                     data-options="iconCls:'icon-manage',plain:true">添加到面板</a>--%>

            <a href="javascript:;" onclick="openEditTable()" class="easyui-linkbutton"
               data-options="iconCls:'icon-edit',plain:true">修改信息</a>
        </div>

        <div style="height: 100%;width: 100%">
            <div class="easyui-dialog" id="columnDesignDig" closed=true modal=true style="height: 450px; width: 1260px;"
                 title="数据表结构一览">
                <table class="easyui-datagrid" id="columnGrid"
                       data-options="toolbar:'#columnToolbar',fit:true,singleSelect:true,rownumbers:true"
                       fitColumns="true" style="height: 100%">
                    <thead>
                    <tr>
                        <th data-options="field:'name', width:100, align:'center'"
                            editor="{type:'validatebox',options:{required:true,validType:'charType'}}">名
                        </th>
                        <th data-options="field:'type', width:100, align:'center'"
                            editor="{type:'combobox',options:{
                            required:true,
                            editable:false,
                            valueField: 'label',
                            textField: 'value',
                            data: [{
                                label: 'NUMBER',
                                value: 'NUMBER'
                            },{
                                label: 'VARCHAR',
                                value: 'VARCHAR'
                            }]}}">类型
                        </th>
                        <th data-options="field:'width', width:100, align:'center'"
                            editor="{type:'numberbox', options: {min: 1,required:true}}">大小
                        </th>
                        <th data-options="field:'point', width:100, align:'center'"
                            editor="{type:'numberbox', options: {min: 0}}">比例
                        </th>
                        <th data-options="field:'notNull', width:60, align:'center'"
                            editor="{type:'checkbox',options:{on:'Y',off:'N'}}">不是null
                        </th>
                        <th data-options="field:'notRepeat', width:60, align:'center'"
                            editor="{type:'checkbox',options:{on:'Y',off:'N'}}">不可重复
                        </th>
                        <th data-options="field:'contextType',width:100,align:'center',
                            formatter: function(value,row,index){
                                if (value == '1'){
                                    return '数字框';
                                } else if (value == '2'){
                                    return '日期框';
                                } else if (value == '3') {
                                    return '下拉框';
                                } else {
                                    return '普通文本框';
                                }
                            }"
                            editor="{type:'combobox',options:{
                            required:true,
                            editable:false,
                            valueField: 'label',
                            textField: 'value',
                            data: [{
                                label: '0',
                                value: '普通文本框'
                            },{
                                label: '1',
                                value: '数字框'
                            },{
                                label: '2',
                                value: '日期框'
                            },{
                                label: '3',
                                value: '下拉框'
                            }]}}">文本框类型
                        </th>
                        <th data-options="field:'dateFormat', width:120, align:'center'"
                            editor="{type:'combobox',options:{
                            required:false,
                            editable:false,
                            valueField: 'label',
                            textField: 'value',
                            data: [{
                                label: 'yyyy-MM-dd',
                                value: 'yyyy-MM-dd'
                            },{
                                label: 'yyyy/MM/dd',
                                value: 'yyyy/MM/dd'
                            },{
                                label: 'yyyy年MM月dd日',
                                value: 'yyyy年MM月dd日'
                            },{
                                label: 'yy-MM-dd',
                                value: 'yy-MM-dd'
                            },{
                                label: 'yy/MM/dd',
                                value: 'yy/MM/dd'
                            },{
                                label: 'yy年MM月dd日',
                                value: 'yy年MM月dd日'
                            },{
                                label: 'yyyy-MM-dd HH:mm:ss',
                                value: 'yyyy-MM-dd HH:mm:ss'
                            }
                            ]}}">日期格式
                        </th>
                        <th data-options="field:'search', width:60, align:'center'"
                            editor="{type:'checkbox',options:{on:'Y',off:'N'}}">搜索条件
                        </th>
                        <th data-options="field:'comment', width:100, align:'center'"
                            editor="{type:'validatebox',options:{required:true,validType:'commentType'}}">中文名
                        </th>
                        <th data-options="field:'comboUrl', width:100, align:'center',formatter: function(value,row,index){
                    if (value == 'null'){
                        return '';
                    } else {
                        return value;
                    }}" editor="{type:'validatebox'}">下拉框地址
                        </th>
                        <th field="action" width="100" align="center" formatter="formatAction">操作</th>
                    </tr>
                    </thead>
                </table>
            </div>

            <div id="confimWidnow" class="easyui-dialog" title="确认"
                 style="height: 350px; width: 350px;text-align: center"
                 data-options="modal:true,collapsible:false,minimizable:false,maximizable:false,closed:true">
                <input type="hidden" name="tableId" id="tableId">
                <div style="width: 100%; text-align: center; margin: 10px 0">
                    <label for="tableName">请输入表英文名：</label><input type="text" name="tableName" id="tableName"/>
                </div>
                <div style="width: 100%; text-align: center;margin: 10px 0">
                    <label for="tableCom">请输入表中文名：</label><input type="text" name="tableCom" id="tableCom"/>
                </div>
                <div style="width: 100%; text-align: center; margin: 10px 0">
                    <label for="uploadFrequency">请输入上传频率：</label>
                    <select class='easyui-combobox' id='uploadFrequency' name='uploadFrequency' editable="false"
                            style='height: 32px;width:181px;'
                            data-options="required:true,url: 'queryDataDictionary?type=1',method: 'get',valueField:'code',
                            textField:'text'"></select>
                </div>
                <div style="width: 100%; text-align: center;margin: 10px 0">
                    <label for="reportStatus">请输入报表状态：</label>
                    <select class='easyui-combobox' id='reportStatus' name='reportStatus' editable="false"
                            style='height: 32px;width:181px;'
                            data-options="required:true,url: 'queryDataDictionary?type=2',method: 'get',valueField:'code',
                            textField:'text'"></select>
                </div>
                <div style="width: 100%; text-align: center;margin: 10px 0">
                    <label>数据源：</label>
                    <select class='easyui-combobox' id='dataSourceId' name='dataSourceId' editable="false"
                            style='height: 32px;width:181px;'
                            data-options="required:true,url: '${serverUrl}/sys_dataSourceList',method: 'get',valueField:'id',
                            textField:'dataSourceName'"></select>
                </div>
                <div style="width: 100%; text-align: center;margin: 10px 0">
                    <label for="tableRemarks" style="vertical-align: middle">请输入备注：</label>
                    <textarea name="tableRemarks" id="tableRemarks" rows="4" cols="30"
                              style="vertical-align: middle;resize: none" maxlength="200"></textarea>
                </div>
                <div style="width: 130px; margin: 10px 0 0 0;display: inline-block">
                    <button onclick="saveTable()">确定</button>
                </div>
                <div style="width: 130px; margin: 10px 0 0 0;display: inline-block">
                    <button onclick="$('#confimWidnow').window('close');">取消</button>
                </div>
            </div>

            <div id="editTable" class="easyui-dialog" title="确认"
                 style="height: 350px; width: 350px;text-align: center"
                 data-options="modal:true,collapsible:false,minimizable:false,maximizable:false,closed:true">
                <input type="hidden" name="tableId" id="editTableId">
                <input type="hidden" name="tableName" id="editTableName"/>
                <input type="hidden" name="tableCom" id="editTableCom"/>
                <div style="width: 100%; text-align: center; margin: 10px 0">
                    <label>上传频率：</label>
                    <select class='easyui-combobox' id='editUploadFrequency' name='uploadFrequency' editable="false"
                            style='height: 32px;width:181px;'
                            data-options="required:true,url: 'queryDataDictionary?type=1',method: 'get',valueField:'code',
                            textField:'text'"></select>
                </div>
                <div style="width: 100%; text-align: center;margin: 10px 0">
                    <label>报表状态：</label>
                    <select class='easyui-combobox' id='editReportStatus' name='reportStatus' editable="false"
                            style='height: 32px;width:181px;'
                            data-options="required:true,url: 'queryDataDictionary?type=2',method: 'get',valueField:'code',
                            textField:'text'"></select>
                </div>
                <div style="width: 100%; text-align: center;margin: 10px 0">
                    <label>数据源：</label>
                    <select class='easyui-combobox' id='editDataSourceId' name='dataSourceId' editable="false"
                            style='height: 32px;width:181px;'
                            data-options="required:true,url: '${serverUrl}/sys_dataSourceList',method: 'get',valueField:'id',
                            textField:'dataSourceName'"></select>
                </div>
                <div style="width: 100%; text-align: center;margin: 10px 0">
                    <label for="editTableRemarks" style="vertical-align: middle">请输入备注：</label>
                    <textarea name="tableRemarks" id="editTableRemarks" rows="4" cols="30"
                              style="resize: none;vertical-align: middle" maxlength="200"></textarea>
                </div>
                <div style="width: 130px; margin: 10px 0 0 0;display: inline-block">
                    <button onclick="editTable()">确定</button>
                </div>
                <div style="width: 130px; margin: 10px 0 0 0;display: inline-block">
                    <button onclick="$('#editTable').window('close');">取消</button>
                </div>
            </div>

            <div id="columnToolbar">
                <a href="javascript:;" id="saveButton" onclick="openConfimWidonw()" class="easyui-linkbutton columnTb"
                   data-options="iconCls:'icon-save',plain:true">保存</a>
                <a href="javascript:;" id="modifyButton" onclick="modifyTable()" class="easyui-linkbutton columnTb"
                   data-options="iconCls:'icon-save',plain:true">保存修改</a>
                <a href="javascript:;" onclick="addColumn()" class="easyui-linkbutton columnTb"
                   data-options="iconCls:'icon-add',plain:true">添加字段</a>
                <a href="javascript:;" onclick="editColumn()" class="easyui-linkbutton columnTb"
                   data-options="iconCls:'icon-edit',plain:true">编辑字段</a>
                <a href="javascript:;" onclick="removeColumn()" class="easyui-linkbutton columnTb"
                   data-options="iconCls:'icon-remove',plain:true">删除字段</a>
                <%--<a href="javascript:;" onclick="exportTemplate()" class="easyui-linkbutton columnTb"
                   data-options="iconCls:'icon-download',plain:true">导出ExceL模板</a>
                <!-- icon-excel -->
                <a href="javascript:;" onclick="importStruct()" class="easyui-linkbutton columnTb"
                   data-options="iconCls:'icon-page-excel',plain:true">Excel导入结构</a>--%>
                <%--<a href="javascript:;" onclick="addKey()" class="easyui-linkbutton" data-options="iconCls:'icon-login',plain:true">主键</a>--%>
            </div>
        </div>
    </div>

    <div id="menuDialog" class="easyui-dialog" title='添加' data-options="toolbar:'#diglogTools',modal:true,closed:true"
         style="height:200px;width:750px;">
        <form id="editForm" method="post">
            <table style="text-align: right;margin: 20px">
                <tr>
                    <td style="width: 300px;">
                        <label>页面名称:</label>
                        <input class="easyui-validatebox" id="viewName" name="viewName" style="height:20px;"
                               data-options="required:true">
                    </td>
                    <td style="width: 300px;">
                        <label>所属系统:</label>
                        <input id="subject" class="easyui-combobox" type="text" name="subject" style="height:20px;"/>
                    </td>
                </tr>
                <tr>
                    <td style="width: 300px;">
                        <label>所属菜单:</label>
                        <input id="resource" class="easyui-combobox" type="text" name="resource" style="height:20px;"
                               data-options="
                            valueField: 'id',
                            textField: 'name',
                            required:true,
                            editable: false
                            "/>
                    </td>
                    <input id="tableSerial" class="easyui-validatebox" type="hidden" name="tableSerial"
                           style="height:20px;"/>
                    <input id="url" class="easyui-validatebox" type="hidden" name="url" style="height:20px;"/>
                </tr>
            </table>
        </form>
    </div>
    <div id="diglogTools">
        <a href="javascript:;" onclick="saveMenu()" class="easyui-linkbutton"
           data-options="iconCls:'icon-save',plain:true">保存</a>
    </div>

    <div id="panelDialog" class="easyui-dialog" title='添加' data-options="toolbar:'#panelTools',modal:true,closed:true"
         style="height:300px;width:500px;">
        <table id="panelGrid" class="easyui-datagrid"
               data-options="url:'${serverUrl}/panel', method:'GET', singleSelect:true, fit:true">
            <thead>
            <tr>
                <th data-options="field:'id',hidden:true"></th>
                <th data-options="field:'panelName',width:480,align:'center'">面板名称</th>
            </tr>
            </thead>
        </table>
    </div>
    <div id="panelTools">
        <a href="javascript:;" onclick="savePanel()" class="easyui-linkbutton"
           data-options="iconCls:'icon-save',plain:true">添加</a>
    </div>

    <%-- 导入模板管理 --%>
    <div id="templateDialog" class="easyui-dialog" title="导入模板管理" modal=true closed=true
         style="width: 1200px; height: 450px;">
        <table id="templateGrid" class="easyui-datagrid"
               data-options="method:'GET',fit:true,toolbar:'#templateToobal',fitColumns:true,singleSelect:true">
            <thead>
            <tr>
                <th data-options="field:'serialNo',width:100,hidden:true"></th>
                <th data-options="field:'templateCont',width:100,hidden:true"></th>
                <th data-options="field:'name',width:100,align:'center'">模板名称</th>
                <th data-options="field:'tableName',width:100,align:'center'">所属数据表</th>
                <th data-options="field:'templateType',width:100,align:'center',formatter: function(value){
                        if (value == '1'){
                            return 'EXCEL';
                        } else if (value == '2') {
                            return 'CSV';
                        } else if (value == '3') {
                            return 'TXT';
                        }
                    }">模板类型
                </th>
                <th data-options="field:'isDefault',width:100,align:'center'">此类型默认模板</th>
                <th data-options="field:'createUser',width:100,align:'center'">创建用户</th>
                <th data-options="field:'createDate',width:100,align:'center'">创建日期</th>
                <th data-options="field:'createTime',width:100,align:'center'">创建时间</th>
            </tr>
            </thead>
        </table>
        <div id="templateToobal">
            <a href="javascript:;" onclick="addTemplate()" class="easyui-linkbutton"
               data-options="iconCls:'icon-add',plain:true">添加模板</a>
            <a href="javascript:;" onclick="rmTemplate()" class="easyui-linkbutton"
               data-options="iconCls:'icon-remove',plain:true">删除模板</a>
            <a href="javascript:;" onclick="setDefault()" class="easyui-linkbutton"
               data-options="iconCls:'icon-logs',plain:true">设置默认</a>
        </div>
    </div>
    <div class="easyui-dialog" id="impDailog" title="导入向导" style="width: 600px;height: 400px;font-size: 15px;"
         data-options='modal:true, closed:true, onBeforeClose:function(){
            $("#switchType").show();
            $("#switchSheet").hide();
            $("#switchFile").hide();
            $("#switchRow").hide();
            $("#switchMap").hide();
            $("#switchOther").hide();
            $("#splitTr").hide();
            $("#charsetTr").hide();
            $("#sheetList").empty();
            $("#uploadFile").val("");
            $("#templateName").val("");
            }' buttons='#importToobar'>
        <div id="switchType" style="width: 93%;height:60%;">
            <p class="infoTitle">您要选择哪种导入格式?</p>
            <fieldset style="width: 100%;height:100%; border: 1px grey dashed">
                <legend>导入类型</legend>
                <input type="radio" name="importType" value="excel"/> Excel文件(*.xls,*.xlsx,*.xlsm)
                <br/>
                <input type="radio" name="importType" value="csv"/> Csv文件(*.csv)
                <br/>
                <input type="radio" name="importType" value="txt"/> 文本文件(*.txt)
            </fieldset>
        </div>
        <div id="switchFile" style="height: 60%;width: 100%;display: none">
            <p class="infoTitle">您必须选择一个文件作为数据源</p>
            <div style="height: 30%;">
                <fieldset style="border: 1px grey dashed">
                    <legend>导入从:</legend>
                    <form id="uploadFileForm" action="${serverUrl}/importExport/resolve" method="POST"
                          enctype="multipart/form-data">
                        <input type="file" id="uploadFile" size="45" name="uploadFile" class="input"
                               onchange="importFileSelected()"/>
                        <input type="hidden" id="handlerType" name="type">
                        <input type="hidden" id="loginId" name="loginId">
                    </form>
                </fieldset>
            </div>

            <div id="switchSheet" style="height:90%;width:100%;margin-top:20px;display: none">
                <fieldset style="border: 1px grey dashed">
                    <legend>选择要导入的Sheet:</legend>
                    <form id="sheetList"></form>
                </fieldset>
            </div>
        </div>
        <div id="switchRow" style="width: 100%;display: none">
            <p class="infoTitle">定义一些附加选项</p>
            <table style="margin-left: 15px;">
                <tr>
                    <td>
                        字段名行：
                    </td>
                    <td>
                        <input type="text" name="headRow" value="1" style="width: 170px; height: 18px;"/>
                    <td>
                </tr>
                <tr>
                    <td>
                        第一个数据行：
                    </td>
                    <td>
                        <input type="text" name="firstRow" value="2" style="width: 170px; height: 18px;"/>
                    </td>
                </tr>
                <tr>
                    <td>
                        最后一个数据行：
                    </td>
                    <td>
                        <input type="text" name="lastRow" style="width: 170px; height: 18px;"/>
                    </td>
                </tr>
                <tr id="splitTr" style="display: none;">
                    <td>
                        字段分割符：
                    </td>
                    <td>
                        <select id="lineSplit" name="lineSplit" editable=false
                                style="width:178px;height:23px;font-size:16px;border: 1px solid black;">
                            <option value=",">,</option>
                            <option value="#">#</option>
                            <option value="~">~</option>
                            <option value="*">*</option>
                            <option value="-">-</option>
                            <option value="^">^</option>
                            <option value="|">|</option>
                        </select>
                    </td>
                </tr>
                <tr id="charsetTr" style="display: none;">
                    <td>
                        请选择编码：
                    </td>
                    <td>
                        <select id="charset" name="charset" editable=false
                                style="width:178px;height:23px;font-size:16px;border: 1px solid black;">
                            <option value="GBK">GBK</option>
                            <option value="UTF-8">UTF-8</option>
                            <option value="GB2312">GB2312</option>
                            <option value="ISO-8859-1">ISO-8859-1</option>
                            <option value="UTF-16">UTF-16</option>
                            <option value="UTF-16BE">UTF-16BE</option>
                            <option value="UTF-16LE">UTF-16LE</option>
                            <option value="UTF-32">UTF-32</option>
                            <option value="UTF-32BE">UTF-32BE</option>
                            <option value="UTF-32LE">UTF-32LE</option>
                        </select>
                    </td>
                </tr>
            </table>
        </div>
        <div id="switchMap" style="width: 100%;height:80%;display: none">
            <p class="infoTitle">您可以指定字段映射，设置映射来指定源字段和目的字段之间的关系</p>
            <div style="margin-left: 15px;">
                源表:
                <div id="sheetSelect">

                </div>
            </div>
            <div style="height: 80%; width:100%;margin-top: 20px;">
                <fieldset style="border: 1px grey dashed">
                    <legend>请选择字段之间的映射关系:</legend>
                    <table id="responseTable"></table>
                </fieldset>
            </div>
        </div>
        <div id="switchOther" style="width: 100%; height: 80%; display: none;">
            <p class="infoTitle">您还需要添加一些关于模板的信息:</p>
            <div style="margin-left: 15px;">
                <label>模板名称</label>
                <input type="text" id="templateName" name="templateName">
                <br>
            </div>
        </div>
    </div>
    <div id="importToobar">
        <a href="javascript:;" onclick="prevStep()" class="easyui-linkbutton"
           data-options="iconCls:'icon-undo',plain:true">上一步</a>
        <a href="javascript:;" onclick="nextStep()" class="easyui-linkbutton"
           data-options="iconCls:'icon-redo',plain:true">下一步</a>
    </div>
</div>


<script type="text/javascript">
    $(function () {
        /**
         * 解决丢它老母的IE缓存问题
         */
        jQuery(function ($) {
            jQuery.ajaxSetup({
                cache: false
            });
        });
        //数据表管理 dataGrid
        $('#tableGrid').datagrid({
            columns: [[
                {field: 'tableId', title: 'Code', width: 200, hidden: true},
                {field: 'tableEN', title: '表名', width: 200, align: 'center'},
                {field: 'tableCN', title: '表中文名', width: 200, align: 'center'},
                {field: 'loginId', title: '创建用户', width: 200, align: 'center'},
                {field: 'uploadFrequency', title: '上传频率', width: 200, align: 'center'},
                {
                    field: 'reportStatus', title: '报表状态', width: 200, align: 'center',
                    formatter: function (value) {
                        if (value == '0') {
                            return '下线';
                        } else if (value == '1') {
                            return '上线';
                        }
                    }
                },
                {
                    field: 'remarks', title: '备注', width: 200, align: 'center', formatter(val) {
                        if (val) {
                            return '<span title="' + val + '">' + val + '</span>';
                        } else {
                            return val;
                        }
                    }
                },
            ]],
            fit: true,
            url: '${serverUrl}/tableManage',
            method: "GET",
            toolbar: "#tableGridToolbar",
            fitColumns: true,
            pagination: true,
            singleSelect: true,
            pageNumber: 1,
            pageSize: 25,
            pageList: [15, 25, 35]
        });
        $("#subject").combobox({
            valueField: 'id',
            textField: 'subjectName',
            editable: false,
            required: true,
            onSelect: function (res) {
                var subjectId = res.id;
                $.ajax({
                    type: "POST",
                    url: "getSys_Menu?subjectId=" + subjectId,
                    contentType: "application/json",
                    dataType: "json",
                    success: function (res) {
                        if (res) {
                            var menulist = res.menulist;
                            var newList = [];
                            for (var i = 0; i < menulist.length; i++) {
                                var menu = menulist[i];
                                if (menu.name == '数据补录') {
                                    newList.push(menu);
                                }
                            }
                            $("#resource").combobox('clear');
                            $("#resource").combobox('loadData', newList);
                        }
                    },
                    error: function (err) {
                        $.messager.alert("提示", "处理失败!", "info");
                    }
                })
            }
        })

        $('#uploadForm').ajaxForm(function (data) {
            if (data.code == '000000') {
                $.messager.alert('提示', "上传成功!", "info");
            } else {
                $.messager.alert('提示', data.msg, "info");
            }
            $("#uploadWidnow").window('close');
            $('#dg').datagrid('reload');
            $.messager.progress('close');
        });
    })

    function queryBytableEnAndtableCn() {
        let tableEn = $("#queryTableEn").val();
        let tableCn = $("#queryTableCn").val();
        $("#tableGrid").datagrid("load", {tableEn: tableEn, tableCn: tableCn});
    }

    function showColumnDesign() {
        var rows = $("#tableGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!', 'info');
            return;
        }
        //打开表结构窗体
        $(".columnTb").hide();
        $("#columnDesignDig").dialog('open');
        $('#columnGrid').datagrid({
            queryParams: {
                tableId: rows[0].tableId,
                dataStatus: '10'
            }
        });
    }


    function addTable() {
        //打开表结构窗体
        $("#tableId").val('');
        $("#tableName").val('');
        $("#tableCom").val('');
        $('#columnGrid').datagrid('load', {});
        $(".columnTb").show();
        $("#modifyButton").hide();
        $("#saveButton").show();
        $("#columnDesignDig").dialog('open');
    }

    function resetTable() {
        var rows = $("#tableGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!', 'info');
            return;
        }
        var tableId = rows[0].tableId;
        var tableName = rows[0].tableEN;
        var tableComment = rows[0].tableCN;
        console.log("tableId=" + tableId + ",tableName=" + tableName + ",tableComment=" + tableComment);
        //获取表中文，与英文名
        $("#tableId").val(tableId);
        $("#tableName").val(tableName);
        $("#tableCom").val(tableComment);
        //打开表结构窗口
        $("#columnDesignDig").dialog('open');
        $('#columnGrid').datagrid({
            queryParams: {
                tableId: tableId,
                dataStatus: '10'
            }
        });
        $(".columnTb").show();
        $("#modifyButton").show();
        $("#saveButton").hide();
    }

    function removeTable() {
        var rows = $("#tableGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!');
            return;
        }
        $.messager.confirm('确认', '您确认要删除该表吗?', function (r) {
            if (r) {
                var data = {
                    "data": {
                        "table": {
                            "tableEN": rows[0].tableEN,
                            "tableId": rows[0].tableId
                        },
                        "columns": []
                    },
                    "logindId": "admin"
                }
                //调用drop接口
                $.ajax({
                    type: "DELETE",
                    url: "${serverUrl}/tableManage",
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify(data),
                    success: function (res) {
                        if (res.code == '000000') {
                            deleteReport(rows[0].tableEN)
                            $.messager.alert("提示", "处理成功!", "info");
                        } else {
                            $.messager.alert("提示", res.msg, "info");
                        }
                        $("#tableGrid").datagrid("reload");
                    },
                    error: function (err) {
                        $.messager.alert("提示", "处理失败!", "info");
                    }
                })
            }
        });
    }

    function deleteReport(tableEN) {
        var parm = {
            "tableEN": tableEN,
        };
        $.ajax({
            type: "POST",
            url: 'delSysReport',
            contentType: 'application/json',
            data: JSON.stringify(parm),
            success: function (result) {
                if (result.code != "000000") {
                    alert(result.msg);
                }
            }
        });
    }

    /**
     * 添加到菜单
     */
    function addToMenu() {
        var rows = $("#tableGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!', "info");
            return;
        }
        var tabldeId = rows[0].tableId;
        //加载系统数据和菜单数据
        $.ajax({
            type: "POST",
            url: "getAllSys_Auth_Role",
            contentType: "application/json",
            dataType: "json",
            success: function (res) {
                if (res) {
                    $("#subject").combobox('clear');
                    $("#subject").combobox('loadData', res.rows);
                }
            },
            error: function (err) {
                $.messager.alert('提示', "处理失败!", "info");
            }
        })
        $("#tableSerial").val(tabldeId);
        $("#url").val("dataMarView?tableId=" + tabldeId);
        $("#menuDialog").dialog('open');
    }

    function saveMenu() {
        if ($("#editForm").form('validate')) {
            $('#editForm').form('submit', {
                url: 'addMenu',
                success: function (res) {
                    if (res.code = '000000') {
                        $.messager.alert("提示", "处理成功,请前往角色管理页面分配权限!", "info");
                    } else {
                        $.messager.alert("提示", res.msg, "info");
                    }
                    $("#menuDialog").dialog('close');
                }
            });
        }
    }

    function openPanelDialog() {
        var rows = $("#tableGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!', "info");
            return;
        }
        $("#panelDialog").dialog("open");
    }

    function savePanel() {
        var rows = $("#tableGrid").datagrid("getSelections");
        var panelRows = $("#panelGrid").datagrid("getSelections");
        if (panelRows.length != 1 || rows.length != 1) {
            $.messager.alert('提示', '请选择一行看板数据进行操作!', "info");
            return;
        }
        var tabldeId = rows[0].tableId;
        var panelId = panelRows[0].id;
        //加载系统数据和菜单数据
        $.ajax({
            type: "POST",
            url: "${serverUrl}/panel/table",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({
                "data": {
                    tableId: tabldeId,
                    panelId: panelId
                },
                "loginId": '${loginId}'
            }),
            success: function (res) {
                if (res.code == "000000") {
                    $.messager.alert('提示', "处理成功", "info");
                } else {
                    $.messager.alert('提示', res.msg, "error");
                }
                $("#panelDialog").dialog('close');
            },
            error: function (err) {
                $.messager.alert('提示', "处理失败!", "info");
            }
        })
    }

    function upLoadeValidate() {
        var rows = $("#tableGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', "请选择一行进行操作!", "info");
            return;
        }
        $.messager.confirm('注意事项', '<span style="color:red;font-size:14px" >' +
            '1、请您仔细核对SQL语句,如有多个查询语句,每条查询语句必须添加分号!<br>' +
            '2、请您将错误信息设置为REASON字段,标识列设置为MARK字段,同时必须包含SERIALNO字段!<br>' +
            '3、请您务必对SQL语句进行优化检查,避免使用子查询,以免慢SQL造成系统性能瓶颈!<br>' +
            '4、请您不要在SQL语句中设置占位符,以免造成SQL注入风险!<br>' +
            '5、请您在书写SQL语句时尽量按照SQL规则,使后期维护更为便捷!<br>' +
            '6、建议您将检查语句定义为视图方便操作!<br>' +
            '7、请您务必在上传前进行测试!<br>' +
            '8、避免中文乱码文件请使用UTF-8编码!' +
            '</span>', function (r) {
            if (r) {
                $("#uploadWidnow").window("open");
            }
        });
    }

    function fileSelected() {
        var file = document.getElementById("uploadCheckFile").files[0];
        var fileName = file.name;
        var fileType = fileName.substring(fileName.lastIndexOf('.'),
            fileName.length);
        if (fileType.toLocaleUpperCase() == ".SQL") {
            if (file) {
                document.getElementById("importId").disabled = "";
            }
        } else {
            $.messager.alert('警告', "上传文件应该是.sql为后缀而不是" + fileType + "请重新选择文件！", "error");
            document.getElementById("importId").disabled = "disabled";
        }
        //填充表单
        var rows = $("#tableGrid").datagrid("getSelections");
        $("#tableCheckId").val(rows[0].tableId);
        $("#loginCheckId").val('${loginId}');
    }
</script>

<script type="text/javascript">


    /**
     * 导入模板管理
     */
    function templateMag() {
        var rows = $("#tableGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!', "info");
            return;
        }
        $('#templateGrid').datagrid({
            url: '${serverUrl}/templateManager',
            queryParams: {
                searchParams: JSON.stringify([{'name': 'TABLEID', 'value': rows[0].tableId}])
            }
        });
        $("#templateDialog").dialog('open');
    }

    /**
     * 删除模板
     */
    function rmTemplate() {
        var rows = $("#templateGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!', "info");
            return;
        }
        var serialNo = rows[0].serialNo;
        $.messager.confirm('确认', '确认要删除该导入模板吗？', function (r) {
            if (r) {
                $.ajax({
                    type: "DELETE",
                    url: "${serverUrl}/templateManager?serialNo=" + serialNo,
                    dataType: "json",
                    success: function (res) {
                        if (res.code == '000000') {
                            $.messager.alert('提示', '处理成功!', "info");
                        } else {
                            $.messager.alert('提示', res.msg, "info");
                        }
                        $("#templateGrid").datagrid("reload");
                    },
                    error: function (err) {
                        $.messager.alert('提示', "处理失败!", "info");
                    }
                })
            }
        });
    }

    /**
     * 设置为默认的导出模板
     */
    function setDefault() {
        var rows = $("#templateGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!', "info");
            return;
        }
        var switchRow = rows[0];
        var serialNo = switchRow.serialNo;
        var type = switchRow.templateType;
        var flag = false; // 是否有默认模板
        //查找下是否有此类型默认模板
        var dataes = $("#templateGrid").datagrid("getRows");
        for (var i = 0; i < dataes.length; i++) {
            if (dataes[i].templateType == type && dataes[i].isDefault == 'Y') {
                flag = true; // 修改状态
            }
        }

        // 判断是否有默认模板
        if (flag) {
            $.messager.confirm('确认', '已有此类型的默认模板,您确定要更改他吗?', function (r) {
                if (r) {
                    sendDefault(serialNo, type);
                }
            });
        } else {
            sendDefault(serialNo, type);
        }
    }

    function sendDefault(serialNo, type) {
        $.ajax({
            type: "PUT",
            url: "${serverUrl}/templateManager?serialNo=" + serialNo + "&type=" + type,
            dataType: "json",
            success: function (res) {
                if (res.code == '000000') {
                    $.messager.alert('提示', '处理成功!', "info");
                } else {
                    $.messager.alert('提示', res.msg, "info");
                }
                $("#templateGrid").datagrid("reload");
            },
            error: function (err) {
                $.messager.alert('提示', "处理失败!", "error");
            }
        })
    }

    var step = null;

    function addTemplate() {
        //获取tableid
        var rows = $("#tableGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!', "info");
            return;
        }
        var tableId = rows[0].tableId;
        step = new Step(tableId);
        console.log(step);
        $("#impDailog").dialog("open");
    }

    function nextStep() {
        step.next();
    }

    function prevStep() {
        step.prev();
    }

    function Step(tableId) {

        Step.prototype.tableId = tableId;

        Step.prototype.data = {data: {}};

        Step.prototype.type = undefined;

        Step.prototype.fileId = undefined;

        Step.prototype.headRow = 1;

        Step.prototype.firstRow = 1;

        Step.prototype.lastRow;

        Step.prototype.split = ',';

        Step.prototype.charset = 'GBK';

        Step.prototype.count = 0;

        Step.prototype.resources = {};

        Step.prototype.columns = [];

        //要导入的sheet 名列表
        Step.prototype.sheets = [];

        Step.prototype.next = function () {
            var handlerStatu = false;
            if (this.count == 0) {
                if (this.switchType()) {
                    $("#switchType").hide();
                    $("#switchFile").show();
                } else {
                    return;
                }
            } else if (this.count == 1) {
                if (this.switchFile()) {
                    $("#switchFile").hide();
                    $("#switchRow").show();
                } else {
                    return;
                }
            } else if (this.count == 2) {
                if (this.switchRow()) {
                    $("#switchMap").show();
                    $("#switchRow").hide();
                } else {
                    return;
                }
            } else if (this.count == 3) {

                $("#switchMap").hide();
                $("#switchOther").show();

            } else if (this.count == 4) {
                if (!this.switchMap()) {
                    return;
                }
            }
            this.count++;
            console.log(this.count);
        }

        Step.prototype.prev = function () {
            var handlerStatu = false;
            if (this.count == 4) {
                $("#switchOther").hide();
                $("#switchMap").show();
            } else if (this.count == 3) {
                $("#switchMap").hide();
                $("#switchRow").show();
            } else if (this.count == 2) {
                $("#switchRow").hide();
                $("#switchFile").show();
            } else if (this.count == 1) {
                $("#switchFile").hide();
                $("#splitTr").hide();
                $("#charsetTr").hide();
                $("#switchSheet").hide();
                $("#sheetList").empty();
                $("#uploadFile").val("");
                $("#switchType").show();
            } else {
                return;
            }
            this.count--;
            console.log(this.count);
        }

        /**
         * 获取导入类型
         */
        Step.prototype.switchType = function () {
            var types = $("#switchType input[name='importType']");
            var val = "";
            for (var i = 0; i < types.length; i++) {
                var type = types[i];
                if (type.checked == true) {
                    val = $(type).val();
                    break;
                }
            }
            if (val == "") {
                $.messager.alert('警告', "请选择导入格式！", "error");
                return false;
            }
            //this.data.data.handlerType = val;
            this.type = val;
            return true;
        }

        Step.prototype.switchFile = function () {
            if (!this.fileId) {
                $.messager.alert('警告', "请选择导入文件", "error");
                return;
            }
            //获取选择的sheet
            if (this.type == 'excel') {
                var checkBoxs = $("#sheetList input[type='checkbox']");
                for (var i = 0; i < checkBoxs.length; i++) {
                    var checkbox = checkBoxs[i];
                    if (checkbox.checked) {
                        this.sheets.push(checkbox.value);
                    }
                }
                if (this.sheets.length <= 0) {
                    $.messager.alert('警告', "请选择要导入的sheet", "error");
                    return false;
                }
            } else if (this.type == "csv" || this.type == "txt") {
                $("#splitTr").show();
                $("#charsetTr").show();
            }
            return true;
        }

        Step.prototype.switchRow = function () {
            //获取行数相关信息
            var headRow = $("#switchRow input[name='headRow']").val();
            var firstRow = $("#switchRow input[name='firstRow']").val();
            var lastRow = $("#switchRow input[name='lastRow']").val();
            var lineSplit = $("#lineSplit").val();
            var charset = $("#charset").val();
            var sheets = this.sheets;
            this.headRow = headRow;
            this.firstRow = firstRow;
            this.lastRow = lastRow;
            this.split = lineSplit;
            this.charset = charset;
            if (!headRow) {
                $.messager.alert('警告', "请输入字段名行", "error");
                return false;
            }
            if (firstRow) {
                firstRow = 2;
            }
            var data = {
                "fileId": this.fileId,
                "handlerType": this.type,
                "spilt": lineSplit,
                "sheets": sheets,
                "headRow": headRow,
                "firstRow": firstRow,
                "lastRow": lastRow
            }
            console.log(data);
            var that = this;
            var defaultName = '';
            //调用后台方法解析头信息
            $.ajax({
                url: '${serverUrl}/importExport/resolve/head',
                type: 'POST',
                async: false,
                dataType: 'JSON',
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (res) {
                    var heads = [];
                    if (res.code == "000000") {
                        var data = res.data;
                        var handlerType = data.handlerType;
                        var resources = {};
                        if ('excel' == handlerType) {
                            sheets = data.excel.sheets;
                            for (var i = 0; i < sheets.length; i++) {
                                var sheet = sheets[i];
                                //处理表头
                                var sheetName = sheet.sheetName;
                                defaultName = sheetName;
                                var heads = sheet.heads;
                                var resource = [];
                                for (var i = 0; i < heads.length; i++) {
                                    var head = heads[i];
                                    resource.push({resource: head, column: '', checked: false});
                                }
                                resources[sheetName] = resource;
                            }
                        }
                        if ('txt' == handlerType || 'csv' == handlerType) {
                            var heads = data.csvOrTxtVo.heads;
                            var resource = [];
                            for (var i = 0; i < heads.length; i++) {
                                var head = heads[i];
                                resource.push({resource: head, column: '', checked: false});
                            }
                            defaultName = "defaultTable";
                            resources[defaultName] = resource;
                        }
                        that.setResources(resources);
                        //that.data.data = data;
                    } else {
                        return false;
                    }
                },
                error: function (error) {
                    $.messager.alert('提示', "处理失败", "error");
                    return false;
                }
            })

            //获取表结构
            $.ajax({
                url: "${serverUrl}/tableManage/column?showHide=false&showBusiness=false&tableId=" + that.getTableId(),
                type: 'GET',
                async: false,
                dataType: 'JSON',
                contentType: "application/json",
                success: function (res) {
                    console.log(res);
                    if (res) {
                        var columns = [];
                        var rows = res.rows;
                        for (var i = 0; i < rows.length; i++) {
                            var row = rows[i];
                            columns.push(row.name);
                        }
                        that.setColumns(columns);
                    } else {
                        $.messager.alert('提示', "无法获取表结构,请重试!", "error");
                        return false;
                    }
                },
                error: function (error) {
                    $.messager.alert('提示', "处理失败", "error");
                    return false;
                }
            })
            //生成Map表格
            var columnSelect = "";
            var columns = that.columns;
            //字段下拉框
            var option = '<select name="column" editable=false style="width: 150px" onchange="columnSelect(this)">';
            option += '<option value=""></option>';
            for (var i = 0; i < columns.length; i++) {
                var c = columns[i];
                option += '<option value="' + c + '">' + c + '</option>';
            }
            option += '</select>';

            //对应的表头
            var resources = that.resources;
            console.log(resources);
            var select = '<select id="sheetOptions" name="sheetOptions" editable=false style="width: 400px" onchange="sheetSelect(this)">>';
            for (var r in resources) {
                select += '<option value="' + r + '">' + r + '</option>';
            }
            select += '</select>';
            var defaultResource = that.resources[defaultName];
            var tr = '<tr><td></td><td>源字段</td><td>目标字段</td></tr>';

            for (var i = 0; i < defaultResource.length; i++) {
                var r = defaultResource[i];
                tr += '<tr><td><input type="checkbox" checked=true name="switchColumn" value="' + r.resource + '"></td>';
                tr += '<td>' + r.resource + '</td>';
                tr += '<td>' + option + '</td></tr>';
            }

            var mapTable = document.getElementById("responseTable");
            mapTable.innerHTML = tr;

            var sheetSelect = document.getElementById("sheetSelect");
            sheetSelect.innerHTML = select;
            $.parser.parse($("#sheetSelect"));
            $.parser.parse($("#responseTable"));
            return true;
        }

        Step.prototype.switchMap = function () {
            //组装请求
            //字段与数据库字段映射
            var resources = this.resources;
            var table = {tableId: this.getTableId()};
            var data = {data: {table: table, fileId: this.fileId, handlerType: this.type}, loginId: '${loginId}'};
            if ('excel' == this.type) {
                var sheetName = this.sheets[0];
                var resource = resources[sheetName];
                var sheet = {sheetName: sheetName};
                sheet.columnMap = resource;
                sheet.headRow = this.headRow;
                sheet.firstRow = this.firstRow;
                sheet.lastRow = this.lastRow;
                data.data.result = sheet;
            }
            if ('csv' == this.type || 'txt' == this.type) {
                var csvOrTxt = {
                    columnMap: this.resources['defaultTable'],
                    headRow: this.headRow,
                    firstRow: this.firstRow,
                    lastRow: this.lastRow,
                    split: this.split,
                    charset: this.charset
                }
                data.data.result = csvOrTxt;
            }
            //模板相关信息
            var templateName = $("#templateName").val();
            data.data.template = {
                name: templateName,
                templateType: this.type,
                tableId: this.getTableId(),
                isDefault: "N"
            };
            console.log(JSON.stringify(data));
            $.messager.progress({text: '正在拼命导入中!'});
            //请求
            $.ajax({
                url: '${serverUrl}/templateManager',
                type: 'POST',
                async: true,
                dataType: 'JSON',
                data: JSON.stringify(data),
                contentType: "application/json",
                success: function (res) {
                    console.log(res);
                    if (res.code == '000000') {
                        $.messager.alert('提示', "导入成功!", "info");
                        $("#impDailog").dialog('close');
                    } else {
                        $.messager.alert('提示', res.msg, "error");
                    }
                    $("#templateGrid").datagrid('reload');
                    $.messager.progress('close');
                },
                error: function (error) {
                    $("#templateGrid").datagrid('reload');
                    $.messager.alert('提示', "处理失败", "error");
                    $.messager.progress('close');
                }
            })
        }

        Step.prototype.setFileId = function (fileId) {
            this.fileId = fileId;
        }

        Step.prototype.setResources = function (resources) {
            this.resources = resources;
        }

        Step.prototype.getResources = function () {
            return this.resources;
        }

        Step.prototype.setColumns = function (columns) {
            this.columns = columns;
        }

        Step.prototype.getTableId = function () {
            return this.tableId;
        }

    }

    function importFileSelected() {
        var file = document.getElementById("uploadFile").files[0];
        var fileName = file.name;
        var fileType = fileName.substring(fileName.lastIndexOf('.'),
            fileName.length);
        var handlerType = step.type;
        if (handlerType == "excel") {
            if (fileType != ".xlsx" && fileType != ".xlsm") {
                $.messager.alert('警告', "上传文件应该是.xlsx或.xlsm为后缀而不是" + fileType + "请重新选择文件！", "error");
                return;
            }
        }

        if (handlerType == "csv") {
            if (fileType != ".csv") {
                $.messager.alert('警告', "上传文件应该是.csv为后缀而不是" + fileType + "请重新选择文件！", "error");
                return;
            }
        }

        if (handlerType == "txt") {
            if (fileType != ".txt") {
                $.messager.alert('警告', "上传文件应该是.txt为后缀而不是" + fileType + "请重新选择文件！", "error");
                return;
            }
        }

        //填充表单并提交
        $("#handlerType").val(handlerType);
        $("#loginId").val('${loginId}');
        $.messager.progress({text: '文件正在解析中......'});
        $("#uploadFileForm").submit();
    }

    function columnSelect(target) {
        var selectSheet = $("#sheetOptions").val();
        var resources = step.getResources();
        var resource = resources[selectSheet];
        var checkbox = $(target).parent().prev().prev().children()[0];
        var name = checkbox.value;
        var checked = checkbox.checked;
        for (var i = 0; i < resource.length; i++) {
            var r = resource[i];
            if (r.resource == name) {
                r.column = $(target).val();
                r.checked = checked;
                break;
            }
        }
    }

    $(function () {
        $('#uploadFileForm').ajaxForm(function (data) {
            var res = data;
            step.setFileId(null);
            if (res.code == '000000') {
                var data = res.data;
                var handlerType = data.handlerType;
                var fileId = data.fileId;
                //设置fileid
                step.setFileId(fileId);
                if (handlerType == "excel") {
                    //$("#switchSheet").show();
                    var excelData = data.excel;
                    var sheets = excelData.sheets;
                    var sheetList = document.getElementById("sheetList");
                    for (var i = 0; i < 1; i++) {
                        var sheet = sheets[i];
                        var input = document.createElement("input");
                        var br = document.createElement("br");
                        var label = document.createElement("label");
                        input.setAttribute("type", "checkbox");
                        input.setAttribute("name", sheet.sheetName);
                        input.setAttribute("value", sheet.sheetName);
                        input.setAttribute("checked", true);
                        label.innerHTML = sheet.sheetName;
                        sheetList.appendChild(input);
                        sheetList.appendChild(label);
                        sheetList.appendChild(br);
                    }
                }
            } else {
                $.messager.alert('提示', res.msg, "info");
            }
            $.messager.progress('close');
        });
    })

</script>

<script type="text/javascript">
    function formatAction(value, row, index) {
        if (row.editing) {
            var s = '<a href="#" onclick="saverow(this)">保存编辑</a> ';
            var c = '<a href="#" onclick="cancelrow(this)">取消编辑</a>';
            return s + c;
        }
    }
</script>
<script type="text/javascript">
    $(function () {
        $('#columnGrid').datagrid({
            method: 'GET',
            url: '${serverUrl}/tableManage/column',
            onBeforeEdit: function (index, row) {
                $(this).datagrid('updateRow', {index: index, row: {editing: true}})
                console.log("onBeforeEdit");
            },
            onAfterEdit: function (index, row) {
                $(this).datagrid('updateRow', {index: index, row: {editing: false}})
                console.log("onAfterEdit");
            },
            onCancelEdit: function (index, row) {
                $(this).datagrid('updateRow', {index: index, row: {editing: false}})
                console.log("onCancelEdit");
            },
        });
    })

    function getRowIndex(target) {
        var tr = $(target).closest('tr.datagrid-row');
        return parseInt(tr.attr('datagrid-row-index'));
    }

    function editColumn() {
        var rows = $("#columnGrid").datagrid("getSelections");
        for (var i = 0; i < rows.length; i++) {
            var rowIndex = $("#columnGrid").datagrid("getRowIndex", rows[i]);
            $('#columnGrid').datagrid('beginEdit', rowIndex);
        }
    }

    function deleterow(target) {
        $('#columnGrid').datagrid('deleteRow', getRowIndex(target));
    }

    function saverow(target) {
        $('#columnGrid').datagrid('endEdit', getRowIndex(target));
    }

    function cancelrow(target) {
        var index = getRowIndex(target);
        var rows = $("#columnGrid").datagrid("getRows");
        if (rows[index].name == undefined) {
            $('#columnGrid').datagrid('deleteRow', index);
        } else {
            $('#columnGrid').datagrid('cancelEdit', index);
        }
    }

    function addColumn() {
        //获取目前table中的总行数
        var rowNum = $('#columnGrid').datagrid('getRows').length;
        //向table中插入一行
        $("#columnGrid").datagrid("appendRow", {});
        //将这一行置为可编辑状态
        $("#columnGrid").datagrid("beginEdit", rowNum);
    }

    function removeColumn() {
        var checkRow = $("#columnGrid").datagrid("getSelected");
        if (!checkRow) {
            //$.messager.alert("提示", "没有可删除的行!", "error");
            return;
        }
        var checkNum = $("#columnGrid").datagrid("getRowIndex", checkRow);
        //console.log("delete num", checkNum);
        if (checkNum > -1) {
            $("#columnGrid").datagrid("deleteRow", checkNum);
        }
    }

    function checkTable() {
        //确认是否有为编辑完成的行
        var page = $("#columnGrid").datagrid("getRows");
        for (var i = 0; i < page.length; i++) {
            var row = page[i];
            if (row.editing) {
                $.messager.alert("提示", "存在未编辑完成的行，请先将其编辑完成!", "error");
                return false;
            }
        }
        //确认是否添加了字段
        var inserted = $("#columnGrid").datagrid("getRows");
        if (inserted.length <= 0) {
            $.messager.alert("提示", "请先添加字段!", "error");
            return false;
        }
        //字段正确性校验
        for (var i = 0; i < inserted.length; i++) {
            var row = inserted[i];
            var columnName = row.name;
            var columnType = row.type;
            var width = Math.floor(row.width);
            var point = Math.floor(row.point ? row.point : 0);
            var textType = row.contextType;
            var columnComment = row.comment;
            var comboUrl = row.comboUrl;
            //判断必填项
            if (columnName == "" || columnType == "" || width == "" ||
                textType == "" || columnComment == "" ||
                columnName == undefined || columnType == undefined || width == undefined ||
                textType == undefined || columnComment == undefined ||
                (textType == "3" && comboUrl == "") ||
                (textType == "3" && comboUrl == undefined)) {
                $.messager.alert("提示", "字段名、类型、大小、文本框类型、中文名与文本框为下拉框时,下拉框地址等字段不能为空!", "error");
                return false;
            }
            if (String(width).indexOf(".") > -1 || String(point).indexOf(".") > -1) {
                $.messager.alert("提示", "字段大小和比例必须为整数!", "error");
                return false;
            }
            //判断长度
            if ('VARCHAR' == columnType) {
                if (width <= 0 || width > 4000) {
                    $.messager.alert("提示", "字段大小必须在1-4000!", "error");
                    return false;
                }
            }
            if ('NUMBER' == columnType) {
                if (width <= 0 || width > 38 || point > 37 || point >= width) {
                    $.messager.alert("提示", "number类型比例不能超过37,大小(含小数)不能超过38,比例不能大于或等于大小!", "error");
                    return false;
                }
            }
            if (!columnName.match(/^\w{1,30}$/)) {
                $.messager.alert("提示", "字段名必须由数字、字母、下划线构成,长度1-30!", "error");
                return false;
            }
            if (!columnComment.match(/^[a-zA-Z0-9\u4E00-\u9FA5\uf900-\ufa2d_]{1,20}$/)) {
                $.messager.alert("提示", "中文名必须由数字、字母、下划线、中文构成,长度1-20!", "error");
                return false;
            }
        }
        return true;
    }

    function openConfimWidonw() {
        //字段校验
        var f = checkTable();
        if (!f) {
            return;
        }
        //打开表名编辑窗口
        $("#confimWidnow").window("open");
    }

    function openEditTable() {
        var rows = $("#tableGrid").datagrid("getSelections");
        if (rows.length != 1) {
            $.messager.alert('提示', '请选择一行数据进行操作!', 'info');
            return;
        }
        var tableId = rows[0].tableId;
        var tableName = rows[0].tableEN;
        var tableComment = rows[0].tableCN;
        var tableRemarks = rows[0].remarks;

        var uploadFrequency = rows[0].uploadFrequency;
        var reportStatus = rows[0].reportStatus;
        var dataSourceId = rows[0].dataSourceId;

        //获取表中文，与英文名
        $("#editTableId").val(tableId);
        $("#editTableName").val(tableName);
        $("#editTableCom").val(tableComment);
        $("#editTableRemarks").val(tableRemarks);

        $('#editUploadFrequency').combobox('setValue', uploadFrequency);
        $('#editReportStatus').combobox('setValue', reportStatus);
        $('#editDataSourceId').combobox('setValue', dataSourceId);
        //打开表名编辑窗口
        $("#editTable").window("open");
    }

    function saveTable() {
        //获取表名
        var tableName = $("#tableName").val();
        var tableCom = $("#tableCom").val();
        var remarks = $("#tableRemarks").val();

        var uploadFrequency = $('#uploadFrequency').combobox("getValue");
        var reportStatus = $('#reportStatus').combobox("getValue");
        var dataSourceId = $('#dataSourceId').combobox("getValue");


        if (uploadFrequency == null || uploadFrequency == '') {
            $.messager.alert("提示", "上传频率是必填项!", "info");
            return;
        }

        if (reportStatus == null || reportStatus == '') {
            $.messager.alert("提示", "报表状态是必填项!", "info");
            return;
        }

        if (dataSourceId == null || dataSourceId == '') {
            $.messager.alert("提示", "数据源是必填项!", "info");
            return;
        }

        //正则校验表名
        if (!tableName.match(/^\w{4,30}$/)
            || !tableCom.match(/^\w{1,20}$|^[\u4e00-\u9fa5,\w]{1,20}$/)) {
            $.messager.alert("提示", "英文名必须由数字、字母、下划线构成,长度4-30,中文名必须由数字、字母、下划线、中文构成,长度1-20!", "info");
            return;
        }
        var inserted = $("#columnGrid").datagrid("getRows");
        var data = {
            "data": {
                "table": {
                    "tableEN": tableName,
                    "tableCN": tableCom,
                    "uploadFrequency": uploadFrequency,
                    "reportStatus": reportStatus,
                    "dataSourceId": dataSourceId,
                    "remarks": remarks
                },
                "columns": inserted
            },
            "loginId": "admin"
        }
        $.messager.progress({
            title: '请稍等',
            msg: '正在保存表...'
        });

        $.ajax({
            type: "POST",
            url: "${serverUrl}/tableManage",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(data),
            success: function (res) {
                $.messager.progress('close');
                if (res.code == '000000') {
                    //添加至报表权限表
                    addToReport(tableName, tableCom, remarks);
                    $.messager.alert("提示", "处理成功!", "info");
                    $("#confimWidnow").window("close");
                    $("#columnDesignDig").dialog("close");
                    $("#tableGrid").datagrid("reload");
                } else {
                    if (res.msg != undefined) {
                        $.messager.alert("提示", res.msg, "info");
                    } else {
                        $.messager.alert("提示", "处理失败!", "info");
                    }
                }
            },
            error: function (err) {
                $.messager.progress('close');
                $.messager.alert("提示", "处理失败!", "error");
            }
        })
    }

    function editTable() {
        //获取表名
        var tableName = $("#editTableName").val();
        var tableCom = $("#editTableCom").val();
        var remarks = $("#editTableRemarks").val();

        var uploadFrequency = $('#editUploadFrequency').combobox("getValue");
        var reportStatus = $('#editReportStatus').combobox("getValue");
        var dataSourceId = $('#editDataSourceId').combobox("getValue");

        if (uploadFrequency == null || uploadFrequency == '') {
            $.messager.alert("提示", "上传频率是必填项!", "info");
            return;
        }

        if (reportStatus == null || reportStatus == '') {
            $.messager.alert("提示", "报表状态是必填项!", "info");
            return;
        }

        if (dataSourceId == null || dataSourceId == '') {
            $.messager.alert("提示", "数据源是必填项!", "info");
            return;
        }

        var data = {
            "data": {
                "table": {
                    "tableEN": tableName,
                    "tableCN": tableCom,
                    "remarks": remarks,
                    "uploadFrequency": uploadFrequency,
                    "reportStatus": reportStatus,
                    "dataSourceId": dataSourceId
                },
                "columns": null
            },
            "loginId": "admin"
        }
        $.messager.progress({
            title: '请稍等',
            msg: '正在保存表...'
        });

        $.ajax({
            type: "POST",
            url: "${serverUrl}/tableManage/editTable",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(data),
            success: function (res) {
                $.messager.progress('close');
                if (res.code == '000000') {
                    //编辑至报表权限表
                    editToReport(tableName, tableCom, remarks, uploadFrequency, reportStatus);
                    $.messager.alert("提示", "处理成功!", "info");
                    $("#editTable").window("close");
                    $("#tableGrid").datagrid("reload");
                } else {
                    if (res.msg != undefined) {
                        $.messager.alert("提示", res.msg, "info");
                    } else {
                        $.messager.alert("提示", "处理失败!", "info");
                    }
                }
            },
            error: function (err) {
                $.messager.progress('close');
                $.messager.alert("提示", "处理失败!", "error");
            }
        })
    }

    function addToReport(tableName, tableCom, remarks) {
        var parm = {
            "tableEN": tableName,
            "tableCom": tableCom,
            "remarks": remarks
        };
        $.ajax({
            type: "POST",
            url: 'addSysReport',
            contentType: 'application/json',
            data: JSON.stringify(parm),
            success: function (result) {
                if (result.code != "000000") {
                    alert(result.msg);
                }
            }
        });
    }

    function editToReport(tableName, tableCom, remarks, uploadFrequency, reportStatus) {
        var parm = {
            "tableEN": tableName,
            "tableCom": tableCom,
            "remarks": remarks,
            "uploadFrequency": uploadFrequency,
            "reportStatus": reportStatus
        };
        $.ajax({
            type: "POST",
            url: 'editSysReport',
            contentType: 'application/json',
            data: JSON.stringify(parm),
            success: function (result) {
                if (result.code != "000000") {
                    alert(result.msg);
                }
            }
        });
    }

    function modifyTable() {
        //字段校验
        var f = checkTable();
        if (!f) {
            return;
        }
        //获取表名
        var tableId = $("#tableId").val();
        var tableName = $("#tableName").val();
        var tableCom = $("#tableCom").val();
        if (tableName == '' || tableCom == '') {
            $.messager.alert("提示", "无法获取修改的表名,请刷新页面重试!", "info");
            return;
        }
        var inserted = $("#columnGrid").datagrid("getRows");
        var data = {
            "data": {
                "table": {
                    "tableEN": tableName,
                    "tableCN": tableCom,
                    "tableId": tableId
                },
                "columns": inserted
            },
            "loginId": "admin"
        }
        $.messager.confirm('确认', '您确认要进行表结构的修改吗?', function (r) {
            if (r) {
                $.ajax({
                    type: "PUT",
                    url: "${serverUrl}/tableManage",
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify(data),
                    success: function (res) {
                        console.log(res);
                        if (res.code == '000000') {
                            $.messager.alert("提示", "处理成功!", "info");
                            $("#columnDesignDig").dialog("close");
                            $("#tableGrid").datagrid("reload");
                        } else {
                            $.messager.alert("提示", res.msg, "info");
                        }
                    },
                    error: function (err) {
                        $.messager.alert("提示", "处理失败!", "info");
                    }
                })
            }
        });
    }


    function exportTemplate() {
        var url = encodeURI("template/ImportTemplate.xlsx");
        window.location.href = url;
    }

    function importStruct() {
        $("#uploadWidnow").window('open');
    }


</script>
<script>
    $.extend($.fn.validatebox.defaults.rules, {
        charType: {
            validator: function (value, param) {
                return value.match(/\w{1,30}/);
            },
            message: '字段名格式不正确'
        },
        commentType: {
            validator: function (value, param) {
                return value.match(/(\w|[\u4e00-\u9fa5]){1,20}/)
            },
            message: '注释格式不正确'
        }
    });
</script>
<%--项目中引用的ajaxUpload bug 太多,版本太旧,不支持跨域，这里替换掉--%>
<script type="text/javascript">
    !function (e) {
        "function" == typeof define && define.amd ? define(["jquery"], e) : "object" == typeof module && module.exports ? module.exports = function (t, r) {
            return void 0 === r && (r = "undefined" != typeof window ? require("jquery") : require("jquery")(t)), e(r), r
        } : e(jQuery)
    }(function (e) {
        "use strict";

        function t(t) {
            var r = t.data;
            t.isDefaultPrevented() || (t.preventDefault(), e(t.target).closest("form").ajaxSubmit(r))
        }

        function r(t) {
            var r = t.target, a = e(r);
            if (!a.is("[type=submit],[type=image]")) {
                var n = a.closest("[type=submit]");
                if (0 === n.length) return;
                r = n[0]
            }
            var i = r.form;
            if (i.clk = r, "image" === r.type) if (void 0 !== t.offsetX) i.clk_x = t.offsetX, i.clk_y = t.offsetY; else if ("function" == typeof e.fn.offset) {
                var o = a.offset();
                i.clk_x = t.pageX - o.left, i.clk_y = t.pageY - o.top
            } else i.clk_x = t.pageX - r.offsetLeft, i.clk_y = t.pageY - r.offsetTop;
            setTimeout(function () {
                i.clk = i.clk_x = i.clk_y = null
            }, 100)
        }

        function a() {
            if (e.fn.ajaxSubmit.debug) {
                var t = "[jquery.form] " + Array.prototype.join.call(arguments, "");
                window.console && window.console.log ? window.console.log(t) : window.opera && window.opera.postError && window.opera.postError(t)
            }
        }

        var n = /\r?\n/g, i = {};
        i.fileapi = void 0 !== e('<input type="file">').get(0).files, i.formdata = void 0 !== window.FormData;
        var o = !!e.fn.prop;
        e.fn.attr2 = function () {
            if (!o) return this.attr.apply(this, arguments);
            var e = this.prop.apply(this, arguments);
            return e && e.jquery || "string" == typeof e ? e : this.attr.apply(this, arguments)
        }, e.fn.ajaxSubmit = function (t, r, n, s) {
            function u(r) {
                var a, n, i = e.param(r, t.traditional).split("&"), o = i.length, s = [];
                for (a = 0; a < o; a++) i[a] = i[a].replace(/\+/g, " "), n = i[a].split("="), s.push([decodeURIComponent(n[0]), decodeURIComponent(n[1])]);
                return s
            }

            function c(r) {
                function n(e) {
                    var t = null;
                    try {
                        e.contentWindow && (t = e.contentWindow.document)
                    } catch (e) {
                        a("cannot get iframe.contentWindow document: " + e)
                    }
                    if (t) return t;
                    try {
                        t = e.contentDocument ? e.contentDocument : e.document
                    } catch (r) {
                        a("cannot get iframe.contentDocument: " + r), t = e.document
                    }
                    return t
                }

                function i() {
                    function t() {
                        try {
                            var e = n(v).readyState;
                            a("state = " + e), e && "uninitialized" === e.toLowerCase() && setTimeout(t, 50)
                        } catch (e) {
                            a("Server abort: ", e, " (", e.name, ")"), s(L), j && clearTimeout(j), j = void 0
                        }
                    }

                    var r = p.attr2("target"), i = p.attr2("action"),
                        o = p.attr("enctype") || p.attr("encoding") || "multipart/form-data";
                    w.setAttribute("target", m), l && !/post/i.test(l) || w.setAttribute("method", "POST"), i !== f.url && w.setAttribute("action", f.url), f.skipEncodingOverride || l && !/post/i.test(l) || p.attr({
                        encoding: "multipart/form-data",
                        enctype: "multipart/form-data"
                    }), f.timeout && (j = setTimeout(function () {
                        T = !0, s(A)
                    }, f.timeout));
                    var u = [];
                    try {
                        if (f.extraData) for (var c in f.extraData) f.extraData.hasOwnProperty(c) && (e.isPlainObject(f.extraData[c]) && f.extraData[c].hasOwnProperty("name") && f.extraData[c].hasOwnProperty("value") ? u.push(e('<input type="hidden" name="' + f.extraData[c].name + '">', k).val(f.extraData[c].value).appendTo(w)[0]) : u.push(e('<input type="hidden" name="' + c + '">', k).val(f.extraData[c]).appendTo(w)[0]));
                        f.iframeTarget || h.appendTo(D), v.attachEvent ? v.attachEvent("onload", s) : v.addEventListener("load", s, !1), setTimeout(t, 15);
                        try {
                            w.submit()
                        } catch (e) {
                            document.createElement("form").submit.apply(w)
                        }
                    } finally {
                        w.setAttribute("action", i), w.setAttribute("enctype", o), r ? w.setAttribute("target", r) : p.removeAttr("target"), e(u).remove()
                    }
                }

                function s(t) {
                    if (!x.aborted && !X) {
                        if ((O = n(v)) || (a("cannot access response document"), t = L), t === A && x) return x.abort("timeout"), void S.reject(x, "timeout");
                        if (t === L && x) return x.abort("server abort"), void S.reject(x, "error", "server abort");
                        if (O && O.location.href !== f.iframeSrc || T) {
                            v.detachEvent ? v.detachEvent("onload", s) : v.removeEventListener("load", s, !1);
                            var r, i = "success";
                            try {
                                if (T) throw "timeout";
                                var o = "xml" === f.dataType || O.XMLDocument || e.isXMLDoc(O);
                                if (a("isXml=" + o), !o && window.opera && (null === O.body || !O.body.innerHTML) && --C) return a("requeing onLoad callback, DOM not available"), void setTimeout(s, 250);
                                var u = O.body ? O.body : O.documentElement;
                                x.responseText = u ? u.innerHTML : null, x.responseXML = O.XMLDocument ? O.XMLDocument : O, o && (f.dataType = "xml"), x.getResponseHeader = function (e) {
                                    return {"content-type": f.dataType}[e.toLowerCase()]
                                }, u && (x.status = Number(u.getAttribute("status")) || x.status, x.statusText = u.getAttribute("statusText") || x.statusText);
                                var c = (f.dataType || "").toLowerCase(), l = /(json|script|text)/.test(c);
                                if (l || f.textarea) {
                                    var p = O.getElementsByTagName("textarea")[0];
                                    if (p) x.responseText = p.value, x.status = Number(p.getAttribute("status")) || x.status, x.statusText = p.getAttribute("statusText") || x.statusText; else if (l) {
                                        var m = O.getElementsByTagName("pre")[0], g = O.getElementsByTagName("body")[0];
                                        m ? x.responseText = m.textContent ? m.textContent : m.innerText : g && (x.responseText = g.textContent ? g.textContent : g.innerText)
                                    }
                                } else "xml" === c && !x.responseXML && x.responseText && (x.responseXML = q(x.responseText));
                                try {
                                    M = N(x, c, f)
                                } catch (e) {
                                    i = "parsererror", x.error = r = e || i
                                }
                            } catch (e) {
                                a("error caught: ", e), i = "error", x.error = r = e || i
                            }
                            x.aborted && (a("upload aborted"), i = null), x.status && (i = x.status >= 200 && x.status < 300 || 304 === x.status ? "success" : "error"), "success" === i ? (f.success && f.success.call(f.context, M, "success", x), S.resolve(x.responseText, "success", x), d && e.event.trigger("ajaxSuccess", [x, f])) : i && (void 0 === r && (r = x.statusText), f.error && f.error.call(f.context, x, i, r), S.reject(x, "error", r), d && e.event.trigger("ajaxError", [x, f, r])), d && e.event.trigger("ajaxComplete", [x, f]), d && !--e.active && e.event.trigger("ajaxStop"), f.complete && f.complete.call(f.context, x, i), X = !0, f.timeout && clearTimeout(j), setTimeout(function () {
                                f.iframeTarget ? h.attr("src", f.iframeSrc) : h.remove(), x.responseXML = null
                            }, 100)
                        }
                    }
                }

                var u, c, f, d, m, h, v, x, y, b, T, j, w = p[0], S = e.Deferred();
                if (S.abort = function (e) {
                    x.abort(e)
                }, r) for (c = 0; c < g.length; c++) u = e(g[c]), o ? u.prop("disabled", !1) : u.removeAttr("disabled");
                (f = e.extend(!0, {}, e.ajaxSettings, t)).context = f.context || f, m = "jqFormIO" + (new Date).getTime();
                var k = w.ownerDocument, D = p.closest("body");
                if (f.iframeTarget ? (b = (h = e(f.iframeTarget, k)).attr2("name")) ? m = b : h.attr2("name", m) : (h = e('<iframe name="' + m + '" src="' + f.iframeSrc + '" />', k)).css({
                    position: "absolute",
                    top: "-1000px",
                    left: "-1000px"
                }), v = h[0], x = {
                    aborted: 0,
                    responseText: null,
                    responseXML: null,
                    status: 0,
                    statusText: "n/a",
                    getAllResponseHeaders: function () {
                    },
                    getResponseHeader: function () {
                    },
                    setRequestHeader: function () {
                    },
                    abort: function (t) {
                        var r = "timeout" === t ? "timeout" : "aborted";
                        a("aborting upload... " + r), this.aborted = 1;
                        try {
                            v.contentWindow.document.execCommand && v.contentWindow.document.execCommand("Stop")
                        } catch (e) {
                        }
                        h.attr("src", f.iframeSrc), x.error = r, f.error && f.error.call(f.context, x, r, t), d && e.event.trigger("ajaxError", [x, f, r]), f.complete && f.complete.call(f.context, x, r)
                    }
                }, (d = f.global) && 0 == e.active++ && e.event.trigger("ajaxStart"), d && e.event.trigger("ajaxSend", [x, f]), f.beforeSend && !1 === f.beforeSend.call(f.context, x, f)) return f.global && e.active--, S.reject(), S;
                if (x.aborted) return S.reject(), S;
                (y = w.clk) && (b = y.name) && !y.disabled && (f.extraData = f.extraData || {}, f.extraData[b] = y.value, "image" === y.type && (f.extraData[b + ".x"] = w.clk_x, f.extraData[b + ".y"] = w.clk_y));
                var A = 1, L = 2, F = e("meta[name=csrf-token]").attr("content"),
                    E = e("meta[name=csrf-param]").attr("content");
                E && F && (f.extraData = f.extraData || {}, f.extraData[E] = F), f.forceSync ? i() : setTimeout(i, 10);
                var M, O, X, C = 50, q = e.parseXML || function (e, t) {
                    return window.ActiveXObject ? ((t = new ActiveXObject("Microsoft.XMLDOM")).async = "false", t.loadXML(e)) : t = (new DOMParser).parseFromString(e, "text/xml"), t && t.documentElement && "parsererror" !== t.documentElement.nodeName ? t : null
                }, _ = e.parseJSON || function (e) {
                    return window.eval("(" + e + ")")
                }, N = function (t, r, a) {
                    var n = t.getResponseHeader("content-type") || "", i = ("xml" === r || !r) && n.indexOf("xml") >= 0,
                        o = i ? t.responseXML : t.responseText;
                    return i && "parsererror" === o.documentElement.nodeName && e.error && e.error("parsererror"), a && a.dataFilter && (o = a.dataFilter(o, r)), "string" == typeof o && (("json" === r || !r) && n.indexOf("json") >= 0 ? o = _(o) : ("script" === r || !r) && n.indexOf("javascript") >= 0 && e.globalEval(o)), o
                };
                return S
            }

            if (!this.length) return a("ajaxSubmit: skipping submit process - no element selected"), this;
            var l, f, d, p = this;
            "function" == typeof t ? t = {success: t} : "string" == typeof t || !1 === t && arguments.length > 0 ? (t = {
                url: t,
                data: r,
                dataType: n
            }, "function" == typeof s && (t.success = s)) : void 0 === t && (t = {}), l = t.method || t.type || this.attr2("method"), (d = (d = "string" == typeof (f = t.url || this.attr2("action")) ? e.trim(f) : "") || window.location.href || "") && (d = (d.match(/^([^#]+)/) || [])[1]), t = e.extend(!0, {
                url: d,
                success: e.ajaxSettings.success,
                type: l || e.ajaxSettings.type,
                iframeSrc: /^https/i.test(window.location.href || "") ? "javascript:false" : "about:blank"
            }, t);
            var m = {};
            if (this.trigger("form-pre-serialize", [this, t, m]), m.veto) return a("ajaxSubmit: submit vetoed via form-pre-serialize trigger"), this;
            if (t.beforeSerialize && !1 === t.beforeSerialize(this, t)) return a("ajaxSubmit: submit aborted via beforeSerialize callback"), this;
            var h = t.traditional;
            void 0 === h && (h = e.ajaxSettings.traditional);
            var v, g = [], x = this.formToArray(t.semantic, g, t.filtering);
            if (t.data) {
                var y = e.isFunction(t.data) ? t.data(x) : t.data;
                t.extraData = y, v = e.param(y, h)
            }
            if (t.beforeSubmit && !1 === t.beforeSubmit(x, this, t)) return a("ajaxSubmit: submit aborted via beforeSubmit callback"), this;
            if (this.trigger("form-submit-validate", [x, this, t, m]), m.veto) return a("ajaxSubmit: submit vetoed via form-submit-validate trigger"), this;
            var b = e.param(x, h);
            v && (b = b ? b + "&" + v : v), "GET" === t.type.toUpperCase() ? (t.url += (t.url.indexOf("?") >= 0 ? "&" : "?") + b, t.data = null) : t.data = b;
            var T = [];
            if (t.resetForm && T.push(function () {
                p.resetForm()
            }), t.clearForm && T.push(function () {
                p.clearForm(t.includeHidden)
            }), !t.dataType && t.target) {
                var j = t.success || function () {
                };
                T.push(function (r, a, n) {
                    var i = arguments, o = t.replaceTarget ? "replaceWith" : "html";
                    e(t.target)[o](r).each(function () {
                        j.apply(this, i)
                    })
                })
            } else t.success && (e.isArray(t.success) ? e.merge(T, t.success) : T.push(t.success));
            if (t.success = function (e, r, a) {
                for (var n = t.context || this, i = 0, o = T.length; i < o; i++) T[i].apply(n, [e, r, a || p, p])
            }, t.error) {
                var w = t.error;
                t.error = function (e, r, a) {
                    var n = t.context || this;
                    w.apply(n, [e, r, a, p])
                }
            }
            if (t.complete) {
                var S = t.complete;
                t.complete = function (e, r) {
                    var a = t.context || this;
                    S.apply(a, [e, r, p])
                }
            }
            var k = e("input[type=file]:enabled", this).filter(function () {
                    return "" !== e(this).val()
                }).length > 0, D = "multipart/form-data", A = p.attr("enctype") === D || p.attr("encoding") === D,
                L = i.fileapi && i.formdata;
            a("fileAPI :" + L);
            var F, E = (k || A) && !L;
            !1 !== t.iframe && (t.iframe || E) ? t.closeKeepAlive ? e.get(t.closeKeepAlive, function () {
                F = c(x)
            }) : F = c(x) : F = (k || A) && L ? function (r) {
                for (var a = new FormData, n = 0; n < r.length; n++) a.append(r[n].name, r[n].value);
                if (t.extraData) {
                    var i = u(t.extraData);
                    for (n = 0; n < i.length; n++) i[n] && a.append(i[n][0], i[n][1])
                }
                t.data = null;
                var o = e.extend(!0, {}, e.ajaxSettings, t, {
                    contentType: !1,
                    processData: !1,
                    cache: !1,
                    type: l || "POST"
                });
                t.uploadProgress && (o.xhr = function () {
                    var r = e.ajaxSettings.xhr();
                    return r.upload && r.upload.addEventListener("progress", function (e) {
                        var r = 0, a = e.loaded || e.position, n = e.total;
                        e.lengthComputable && (r = Math.ceil(a / n * 100)), t.uploadProgress(e, a, n, r)
                    }, !1), r
                }), o.data = null;
                var s = o.beforeSend;
                return o.beforeSend = function (e, r) {
                    t.formData ? r.data = t.formData : r.data = a, s && s.call(this, e, r)
                }, e.ajax(o)
            }(x) : e.ajax(t), p.removeData("jqxhr").data("jqxhr", F);
            for (var M = 0; M < g.length; M++) g[M] = null;
            return this.trigger("form-submit-notify", [this, t]), this
        }, e.fn.ajaxForm = function (n, i, o, s) {
            if (("string" == typeof n || !1 === n && arguments.length > 0) && (n = {
                url: n,
                data: i,
                dataType: o
            }, "function" == typeof s && (n.success = s)), n = n || {}, n.delegation = n.delegation && e.isFunction(e.fn.on), !n.delegation && 0 === this.length) {
                var u = {s: this.selector, c: this.context};
                return !e.isReady && u.s ? (a("DOM not ready, queuing ajaxForm"), e(function () {
                    e(u.s, u.c).ajaxForm(n)
                }), this) : (a("terminating; zero elements found by selector" + (e.isReady ? "" : " (DOM not ready)")), this)
            }
            return n.delegation ? (e(document).off("submit.form-plugin", this.selector, t).off("click.form-plugin", this.selector, r).on("submit.form-plugin", this.selector, n, t).on("click.form-plugin", this.selector, n, r), this) : this.ajaxFormUnbind().on("submit.form-plugin", n, t).on("click.form-plugin", n, r)
        }, e.fn.ajaxFormUnbind = function () {
            return this.off("submit.form-plugin click.form-plugin")
        }, e.fn.formToArray = function (t, r, a) {
            var n = [];
            if (0 === this.length) return n;
            var o, s = this[0], u = this.attr("id"),
                c = t || void 0 === s.elements ? s.getElementsByTagName("*") : s.elements;
            if (c && (c = e.makeArray(c)), u && (t || /(Edge|Trident)\//.test(navigator.userAgent)) && (o = e(':input[form="' + u + '"]').get()).length && (c = (c || []).concat(o)), !c || !c.length) return n;
            e.isFunction(a) && (c = e.map(c, a));
            var l, f, d, p, m, h, v;
            for (l = 0, h = c.length; l < h; l++) if (m = c[l], (d = m.name) && !m.disabled) if (t && s.clk && "image" === m.type) s.clk === m && (n.push({
                name: d,
                value: e(m).val(),
                type: m.type
            }), n.push({name: d + ".x", value: s.clk_x}, {
                name: d + ".y",
                value: s.clk_y
            })); else if ((p = e.fieldValue(m, !0)) && p.constructor === Array) for (r && r.push(m), f = 0, v = p.length; f < v; f++) n.push({
                name: d,
                value: p[f]
            }); else if (i.fileapi && "file" === m.type) {
                r && r.push(m);
                var g = m.files;
                if (g.length) for (f = 0; f < g.length; f++) n.push({
                    name: d,
                    value: g[f],
                    type: m.type
                }); else n.push({name: d, value: "", type: m.type})
            } else null !== p && void 0 !== p && (r && r.push(m), n.push({
                name: d,
                value: p,
                type: m.type,
                required: m.required
            }));
            if (!t && s.clk) {
                var x = e(s.clk), y = x[0];
                (d = y.name) && !y.disabled && "image" === y.type && (n.push({
                    name: d,
                    value: x.val()
                }), n.push({name: d + ".x", value: s.clk_x}, {name: d + ".y", value: s.clk_y}))
            }
            return n
        }, e.fn.formSerialize = function (t) {
            return e.param(this.formToArray(t))
        }, e.fn.fieldSerialize = function (t) {
            var r = [];
            return this.each(function () {
                var a = this.name;
                if (a) {
                    var n = e.fieldValue(this, t);
                    if (n && n.constructor === Array) for (var i = 0, o = n.length; i < o; i++) r.push({
                        name: a,
                        value: n[i]
                    }); else null !== n && void 0 !== n && r.push({name: this.name, value: n})
                }
            }), e.param(r)
        }, e.fn.fieldValue = function (t) {
            for (var r = [], a = 0, n = this.length; a < n; a++) {
                var i = this[a], o = e.fieldValue(i, t);
                null === o || void 0 === o || o.constructor === Array && !o.length || (o.constructor === Array ? e.merge(r, o) : r.push(o))
            }
            return r
        }, e.fieldValue = function (t, r) {
            var a = t.name, i = t.type, o = t.tagName.toLowerCase();
            if (void 0 === r && (r = !0), r && (!a || t.disabled || "reset" === i || "button" === i || ("checkbox" === i || "radio" === i) && !t.checked || ("submit" === i || "image" === i) && t.form && t.form.clk !== t || "select" === o && -1 === t.selectedIndex)) return null;
            if ("select" === o) {
                var s = t.selectedIndex;
                if (s < 0) return null;
                for (var u = [], c = t.options, l = "select-one" === i, f = l ? s + 1 : c.length, d = l ? s : 0; d < f; d++) {
                    var p = c[d];
                    if (p.selected && !p.disabled) {
                        var m = p.value;
                        if (m || (m = p.attributes && p.attributes.value && !p.attributes.value.specified ? p.text : p.value), l) return m;
                        u.push(m)
                    }
                }
                return u
            }
            return e(t).val().replace(n, "\r\n")
        }, e.fn.clearForm = function (t) {
            return this.each(function () {
                e("input,select,textarea", this).clearFields(t)
            })
        }, e.fn.clearFields = e.fn.clearInputs = function (t) {
            var r = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;
            return this.each(function () {
                var a = this.type, n = this.tagName.toLowerCase();
                r.test(a) || "textarea" === n ? this.value = "" : "checkbox" === a || "radio" === a ? this.checked = !1 : "select" === n ? this.selectedIndex = -1 : "file" === a ? /MSIE/.test(navigator.userAgent) ? e(this).replaceWith(e(this).clone(!0)) : e(this).val("") : t && (!0 === t && /hidden/.test(a) || "string" == typeof t && e(this).is(t)) && (this.value = "")
            })
        }, e.fn.resetForm = function () {
            return this.each(function () {
                var t = e(this), r = this.tagName.toLowerCase();
                switch (r) {
                    case"input":
                        this.checked = this.defaultChecked;
                    case"textarea":
                        return this.value = this.defaultValue, !0;
                    case"option":
                    case"optgroup":
                        var a = t.parents("select");
                        return a.length && a[0].multiple ? "option" === r ? this.selected = this.defaultSelected : t.find("option").resetForm() : a.resetForm(), !0;
                    case"select":
                        return t.find("option").each(function (e) {
                            if (this.selected = this.defaultSelected, this.defaultSelected && !t[0].multiple) return t[0].selectedIndex = e, !1
                        }), !0;
                    case"label":
                        var n = e(t.attr("for")), i = t.find("input,select,textarea");
                        return n[0] && i.unshift(n[0]), i.resetForm(), !0;
                    case"form":
                        return ("function" == typeof this.reset || "object" == typeof this.reset && !this.reset.nodeType) && this.reset(), !0;
                    default:
                        return t.find("form,input,label,select,textarea").resetForm(), !0
                }
            })
        }, e.fn.enable = function (e) {
            return void 0 === e && (e = !0), this.each(function () {
                this.disabled = !e
            })
        }, e.fn.selected = function (t) {
            return void 0 === t && (t = !0), this.each(function () {
                var r = this.type;
                if ("checkbox" === r || "radio" === r) this.checked = t; else if ("option" === this.tagName.toLowerCase()) {
                    var a = e(this).parent("select");
                    t && a[0] && "select-one" === a[0].type && a.find("option").selected(!1), this.selected = t
                }
            })
        }, e.fn.ajaxSubmit.debug = !1
    });
</script>
</body>
</html>